import http from './interface'
import {
    TRADE_METHOD,
    STD_AUTH_PROVIDER
} from './const'

/**
 * 将业务所有接口统一起来便于维护
 * 如果项目很大可以将 url 独立成文件，接口分成不同的模块
 * 
 */
//设置baseUrl
http.config.baseUrl = "https://api.chik.cn/"
// http.config.baseUrl = "http://dy.ngrok.chik.cn/"
// http.config.baseUrl = "http://localhost:8181/"

const AUTH_TOKEN = "auth_token";
const KEY_HEADER_TOKEN = 'apiusertoken';
const KEY_HEADER_TOKEN_TYPE = 'apptype';
const DEFAULT_BID = "10000";

// #ifdef MP-WEIXIN
const PLATFORM_FLAG = TRADE_METHOD.WX_JSAPI_MINI;
// #endif
// #ifdef MP-TOUTIAO
const PLATFORM_FLAG = TRADE_METHOD.TT_JSAPI_MINI;
// #endif


// 单独导出(测试接口) import {test} from '@/common/vmeitime-http/'
export const test = (data) => {
    return http.request({
        baseUrl: 'https://unidemo.dcloud.net.cn/',
        url: 'ajax/echo/text?name=uni-app',
        dataType: 'text',
        data,
    })
}

// ---- 基础授权业务 ---------------------------------------
export const baseToken = () => {
    return new Promise((resolve, reject) => {
        http.request({
            url: 'v1/oauth/createAuthCode',
            method: 'POST',
            data: {
                businessId: DEFAULT_BID,
                userId: "888"
            }
        }).then((res) => {
            console.log("基础授权通过", res.data);
            uni.setStorageSync("baseAuthCode", res.data);
            resolve(res);
        }).catch((err) => {
            uni.showToast({
                icon: 'error',
                position: 'bottom',
                title: '基础授权失败!'
            });
            reject(err);
        });
    });
}

export const baseLogin = (baseAuthCode) => {
    return new Promise((resolve, reject) => {
        thirdLogin().then(thirdAuthCode => {
            let postData = {
                platform: PLATFORM_FLAG,
                businessId: DEFAULT_BID,
                data: baseAuthCode
            };
            Object.assign(postData, {
                authCode: thirdAuthCode.code
            });
            http.request({
                url: 'v1/oauth/authCodeLogin',
                method: 'POST',
                data: postData
            }).then((response) => {
                console.log('获取token 结果:', response.data);
                console.log("openId", response.data.openId);
                console.log("token", response.data.token);
                const token = response.data.token;
                uni.setStorageSync(AUTH_TOKEN, token);

                let userInfo = {
                    'sessionid': response.data.openId,
                    'wxInfo': '',
                    'memberInfo': ''
                };
                uni.setStorageSync('userInfo', userInfo);
                uni.setStorageSync("share_openid", userInfo.sessionid);
                resolve(response.data);
            }).catch((error) => {
                console.error("BASE_LOGIN error", error)
                reject(error);
            })
        }).catch(err => {
            console.error("THIRD_LOGIN error", err)
            reject(err);
        });
    });
}

export const thirdLogin = () => {
    return new Promise((resolve, reject) => {

        let providerId = STD_AUTH_PROVIDER.WECHAT.NAME;
        // #ifdef MP-TOUTIAO
        providerId = STD_AUTH_PROVIDER.TOUTIAO.NAME;
        // #endif

        uni.getProvider({
            service: 'oauth',
            success: function(res) {
                console.log(res.provider)
                if (res.provider.indexOf(providerId) == -1) {
                    uni.showToast({
                        title: '未找到匹配的授权方式',
                        icon: 'none',
                        duration: 2000
                    })
                    return;
                }

                uni.login({
                    provider: providerId,
                    scopes: 'auth_user', // 'auth_base',
                    success: function(res) {
                        const thirdAuthCodeData = {}; // 存储数据结构与APP端保持一致
                        console.log("providerId | ", providerId, res)
                        Object.assign(thirdAuthCodeData, {
                            code: res.code || res.authCode
                        });
                        resolve(thirdAuthCodeData);
                    },
                    fail: function(err) {
                        console.error(err);
                    }
                });
            }
        });
    });
}

export const userInfo = (data) => {
    return http.request({
        url: 'v1/oauth/getUserInfo',
        method: 'GET',
        data,
    })
}

export const bindOpenUser = (data) => {
    let authType = STD_AUTH_PROVIDER.WECHAT.NAME;
    // #ifdef MP-TOUTIAO
    authType = STD_AUTH_PROVIDER.TOUTIAO.NAME;
    // #endif
    return http.request({
        url: 'v1/oauth/bindOpenUser/' + authType,
        method: 'GET',
        data,
    })
}

export const authDouyinOpenAuth = (data) => {
    return http.request({
        url: 'v1/oauth/authDouyinOpenAuth',
        method: 'GET',
        data,
    })
}


//设置请求前拦截器
http.interceptor.request = (config) => {
    console.log('个性化request....', config)

    let memToken = uni.getStorageSync(AUTH_TOKEN);
    if (!memToken) {
        console.error("memToken 不存在");
        config.header = {};
    } else {
        console.log("memToken 输出 ", memToken);
        //添加通用参数
        config.header = {
            [KEY_HEADER_TOKEN_TYPE]: 1,
            [KEY_HEADER_TOKEN]: memToken
        }
    }
}

//设置请求结束后拦截器
http.interceptor.response = (response) => {
    console.log('个性化response....', response)
    if (response.statusCode != 200) {
        return response;
    }
    if (response.data.status == 1100 || response.data.status == 2000) {
        uni.showLoading({
            mask: true,
            title: '授权登录中...',
        })
        let baseAuthCode = uni.getStorageSync("baseAuthCode");
        if (!baseAuthCode) {
            baseToken().then(() => {
                uni.hideLoading();
            });
            return;
        }
        baseLogin(baseAuthCode).then(() => {
            uni.hideLoading();
        });
    }
    //判断返回状态 执行相应操作
    return response.data;
}

// ---- 菜谱业务 ---------------------------------------
export const uploadImg = (filePath, mediaType) => {
    return new Promise((resolve, reject) => {
        console.log("上传参数1", filePath, mediaType);
        var uploadTask = uni.uploadFile({
            url: http.config.baseUrl + 'v1/oss/upload',
            filePath: filePath,
            fileType: mediaType,
            name: 'file',
            formData: {
                path: 'chik',
                type: mediaType,
                'success_action_status': '200',
            },
            success: res => {
                console.log("上传结果", res)
                if (res && res.statusCode != 200) {
                    uni.showToast({
                        icon: 'none',
                        title: '上传失败'
                    })
                    reject(res)
                } else if (res && res.statusCode == 200) {
                    resolve(JSON.parse(res.data))
                }
            },
            fail: err => {
                console.log("上传失败", err);
                uni.showToast({
                    icon: 'none',
                    title: '上传失败'
                })
                reject(err)
            }
        })
    })
}

// 轮播图
export const banner = (data) => {
    return http.request({
        url: 'v1/bookFrontend/searchBook',
        method: 'POST',
        data,
    })
}
export const searchBook = (data) => {
    return http.request({
        url: 'v1/bookFrontend/searchBook',
        method: 'POST',
        data,
    })
}
export const bookDetail = (data) => {
    return http.request({
        url: 'v1/bookFrontend/queryBookDetail',
        method: 'GET',
        data,
    })
}

export const createMp4 = (data) => {
    return http.request({
        url: 'v1/video/createMp4',
        method: 'POST',
        timeout: 10000, // 超时时间4分钟
        data,
    })
}

export const collect = (data) => {
    return http.request({
        url: 'v1/userBookFrontend/collect',
        method: 'GET',
        data,
    })
}
export const collectListByPage = (data) => {
    return http.request({
        url: 'v1/userBookFrontend/collectListByPage',
        method: 'POST',
        data,
    })
}
export const worksListByPage = (data) => {
    return http.request({
        url: 'v1/userBookFrontend/worksListByPage',
        method: 'POST',
        data,
    })
}
export const saveBook = (data) => {
    return http.request({
        url: 'v1/userBookFrontend/saveBook',
        method: 'POST',
        data,
    })
}

export const publish = (data) => {
    return http.request({
        url: 'v1/userBookFrontend/publish',
        method: 'GET',
        data,
    })
}

// 默认全部导出  import api from '@/common/vmeitime-http/'
export default {
    http,
    baseToken,
    baseLogin,
    thirdLogin,
    userInfo,
    bindOpenUser,
    authDouyinOpenAuth,

    banner,
    searchBook,
    bookDetail,
    createMp4,
    collect,
    collectListByPage,
    worksListByPage,
    publish,
    uploadImg,
    saveBook
}
